const request = require("request");
const qqinfo = {
    APP_ID: "101353443",
    APP_KEY: "fdc014c82e46f611ef7eef0009b7a2e7",
    REDIRECT_URI: "http://editor.makelouden.cc/user/setToken/qq"
}

const setToken = (req, res, cb) => {
    /*
    http://editor.makelouden.cc/user/setToken/qq?code=106F95F473BF91CF118C5903DE2583EC&state=vJRzivds2C7BzUTEd6ZyOY2i5-DLsq8g
    */
    var sid = req.query.state;
    var code = req.query.code;
    var url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=" + qqinfo.APP_ID + "&client_secret=" + qqinfo.APP_KEY + "&code=" + code + "&state=" + sid + "&redirect_uri=" + qqinfo.REDIRECT_URI;
    // console.log(url);
    request(url, (err, response, body) => {
        if (err) {
            res.send(JSON.stringify({
                result: -1,
                msg: "登陆错误，请重试",
                // err: err
            }));
            console.error(err);
            return;
        }
        // access_token=YOUR_ACCESS_TOKEN&expires_in=3600
        var body1 = {}
        var args = body.split('&');
        for (let k in args) {
            var arg = args[k].split('=');
            body1[arg[0]] = arg[1];
        }
        body = body1;

        let getUserInfo = (body3) => {
            var url2 = "https://graph.qq.com/user/get_user_info?access_token=" + body.access_token + "&oauth_consumer_key=" + qqinfo.APP_ID + "&openid=" + body3.openid;
            // console.log(url2);
            request(url2, (err, response, body2) => {
                if (err) {
                    res.send(JSON.stringify({
                        result: -1,
                        msg: "登陆错误，请重试",
                        // err: err
                    }));
                    console.error(err);
                } else {
                    body2 = JSON.parse(body2);
                    // console.log(body2);
                    var sessionStore = req.sessionStore;
                    sessionStore.load(sid, (err, sess) => {
                        if (err) {
                            res.redirect(301, '/close.html');
                            console.error(err);
                        } else if (!sess) {
                            res.redirect(301, '/close.html');
                        } else if (body2.errcode) {
                            // console.log(body2);
                            res.send(JSON.stringify({
                                result: -1,
                                msg: "登陆错误，请重试",
                                // err: err
                            }));
                            console.error(errcode);
                        } else {
                            sess.userInfo = {
                                userType: "qq",
                                id: "qq_" + body3.openid,
                                nickname: body2.nickname,
                                verified: true,
                                prop: body2
                            };
                            sess.save((err) => {
                                if (err) {
                                    console.error(err);
                                }
                            });
                            res.redirect(301, '/close.html');
                            // console.log("set token " + sess.id);
                            // console.log(sess);
                            cb(sess.userInfo);
                        }
                    });
                }
            });
        };
        // https://graph.qq.com/oauth2.0/me?access_token=YOUR_ACCESS_TOKEN
        var urlMe = "https://graph.qq.com/oauth2.0/me?access_token=" + body.access_token;
        request(urlMe, (err, response, body3) => {
            if (err) {
                res.send(JSON.stringify({
                    result: -1,
                    msg: "登陆错误，请重试",
                    // err: err
                }));
                console.error(err);
            } else {
                // console.log(body3);
                var callback = getUserInfo;
                eval(body3);
            }
        });
    });
}
module.exports.setToken = setToken;


/*
function login(userInfo,callback) {
    if (userInfo.userType !== "qq") {
       console.error("not a qq user");
    }
    var prop = userInfo.prop;
    var openId = prop.openId;
    var accessToken = prop.accessToken;
    var url = "https://graph.qq.com/user/get_user_info?access_token=" + accessToken + "&oauth_consumer_key=" + APP_ID + "&openid=" + openId;
    console.log(" !! login qq openId:"+openId);
    request(url, function (error, response, body) {
        console.log(" !! login qq callback openId:"+openId);
		console.log(body);
        if(err){
           console.error(err);
            callback(false);
            return;
        }
        if(body.ret<0){
            callback(-1,"验证失败");
        }else{
            callback(0);
        }
    });
}
exports.login = login;
*/